<template>
  <view class="content">
    <!-- 头部 -->
    <top-bar @searchInGoods="searchGoods"></top-bar>
    <!-- 商品列表 -->
    <view class="main flex">
      <view class="main_left_cont">
        <k-dropdown  @updateOption="fillterData"></k-dropdown>
        <view class="main_list">
          <view class="main_tit">
            <view class="main_line"></view>
            <view class="main_txt">{{ categoryName }}</view>
          </view>
          <view class="main_items flex" v-if="goodsList.length > 0">
            <view class="main_item" v-for="(item, idx) in goodsList" :key="idx" @tap="addCart(item)">
              <image lazy-load class="main_src" mode="aspectFill" :src="item.thumb + '?imageView2/1/w/576/h/576/q/75'"></image>
              <view class="main_info">
                <view class="main_name">{{ item.title }}</view>
                <view class="main_ename ell2">{{ item.subtitle }}</view>
                <view class="main_box flex">
                  <view class="flex">
                    <view class="main_price">
                      <text>￥</text>
                      {{ item.price }}
                    </view>
                    <view class="sale_price" v-if="Number(item.original_price)">￥{{ item.original_price }}</view>
                  </view>
                  <view class="main_add">+</view>
                </view>
              </view>
              <image lazy-load v-if="!item.stock" mode="aspectFill" class="sale-out" src="../../static/img/sale_out.png"></image>
              <image lazy-load v-if="item.is_top" mode="aspectFill" class="is-top" src="../../static/img/top.png"></image>
            </view>						
          </view>
					<view class="main_items flex" v-else-if="goodsList.length==0 && isLoaded">
						<view class="noneGoods">暂无品类可选</view>
					</view>
        </view>
      </view>
      <view class="main_right_cont">
        <view v-for="(item, index) in categoryList" :key="index" :class="categoryIdx == item.id ? 'r_item addStyle' : 'r_item'" 
				@click="changeCategory(item.id, item.name)">{{ item.name }}</view>
      </view>
    </view>
    <!-- 商品详情 -->
    <goods-detail v-if="cartShow" :goodsId="goodsId" :isPackage="isPackage" @cartIsShow="cartIsShow" :inte="0"></goods-detail>
  </view>
</template>

<script>
import goodsDetail from '@/components/goodsDetail.vue';
import topBar from '@/components/topBar.vue';
import kDropdown from '@/components/dropdown.vue';
import { debounce } from '@/common/util.js';
import { GOODS_LIST_INDEX, GOODS_BACKAGE, GOODS_CATEGORY_LIST, GOODS_LIST, GOODS_DETAIL, STORE_GET_INFO } from '@/api';
export default {
  name: 'IndexPage',
  components: {
    topBar,
    goodsDetail,
    kDropdown
  },
  data() {
    return {
      goodsId: null,
      cartShow: false,
      isPay: false,
      goodsList: [],
      categoryIdx: -2,
      categoryName: '精品推荐',
      categoryList: [{id: -2, name: '精品推荐'}],
      storeId: this.$store.state.storeConf.store_id,
      finished: false,
      listQuery: {
        page: 1,
        pageSize: 12
      },
			pages:'',//总页数
      styleActive: {},
      placeActive: {},
      volActive: {},
      priceActive: {},
      isPackage: false,
      isLoaded:false, //加载未完成
      goodsType: 'top',
      gids: null
    };
  },
  beforeDestroy() {
    this.$store.commit('setkeywords', '')
	this.$store.commit('setcategory', -1);
  },
  onLoad: function(options) {
	if (options) {
		console.log(options.id)
		if (options.id) {
			let url = GOODS_DETAIL;
			this.$_get(url, {
				id: options.id
			}).then(res => {
				if (res.msg == '获取成功') {
					var g = {
						id: options.id,
						is_package: res.is_package
					}
					this.addCart(g)
				} else {
				}
			});	
		}
	}
  },
  mounted() {
    let that = this
    setTimeout(() => {
      that.getStoreInfo();
      let keywords = that.$store.state.keywords
      if (keywords) {
        that.searchGoods()
      } else {
        that.getGoodsListIndex();
      }
    }, 200)
  },
  onReachBottom(){ //上拉加载
    let that = this
		console.log(that.finished, 'sadadsadasdsderwerwerwedsfsdf')
		if (!that.finished) {
			if(that.listQuery.page <= that.pages){
				if (that.goodsType === 'top') {
					that.getGoodsListIndex()
				} else if (that.goodsType === 'package') {
					that.getGoodsBackage()
				} else if (that.goodsType === 'general') {
					that.getGoodsList()
				}
			}
		}
  },
  methods: {
    // 搜索
    searchGoods () {
      let that = this
      that.categoryName = '搜索结果'
      that.listQuery.page = 1
      that.isLoaded=false
      that.goodsList = []
      that.getGoodsList()
    },
    // 商品列表首次随机加载
    getGoodsListIndex() {
      let that = this;
      uni.showLoading()
      let qsData = {
        store_id: that.storeId,
        page: that.listQuery.page,
        limit: that.listQuery.pageSize,
        gids: that.gids
      };
      that.$_get(GOODS_LIST_INDEX, qsData).then(res => {
        if (res.code === 1) {
          that.pages =	Math.ceil((res.data.count) / (that.listQuery.pageSize))//总页数
          that.goodsList = that.goodsList.concat(res.data.list)
          that.gids = res.data.gids
          if (res.data.list.length < that.listQuery.pageSize) {
            that.finished = true
          } else {
            that.listQuery.page++
          }
        } else {
          that.$common.msgToShow(res.msg)
        }
				that.isLoaded=true
        that.loading = false
				uni.hideLoading()
      });
    },
    // 商品列表
    getGoodsList() {
      let that = this;
			let page = that.listQuery.page
      let qsData = {
        store_id: that.storeId,
        page: that.listQuery.page,
        limit: that.listQuery.pageSize,
        keywords: that.$store.state.keywords == 'null' ? '' : this.$store.state.keywords
      };

      if (that.categoryIdx && that.categoryIdx !== -2) {
        qsData.category_id = that.categoryIdx
      }

      if (that.styleActive && that.styleActive.id >= 0) {
        qsData.style_id = that.styleActive.id
      }
      if (that.placeActive && that.placeActive.id >= 0) {
        qsData.place_id = that.placeActive.id
      }

      if (that.volActive && that.volActive.type && that.volActive.name !== '全部') {
        qsData.min_degree = that.volActive.min
        qsData.max_degree = that.volActive.max
      }
      if (that.priceActive && that.priceActive.type && that.priceActive.name !== '全部') {
        qsData.min_price = that.priceActive.min
        qsData.max_price = that.priceActive.max
      }

      that.$_get(GOODS_LIST, qsData).then(res => {
        if (res.code === 1) {
          that.goodsList = that.goodsList.concat(res.data.list)
					console.log(res.data.list.length, 'xinqianqiqiiqiqiqqi', that.listQuery.pageSize)
          if (res.data.list.length < that.listQuery.pageSize) {
            that.finished = true
          } else {
						page = page + 1
            that.listQuery.page = page
						console.log(page)
          }
        } else {
          that.$common.msgToShow(res.msg)
        }
        // this.$common.loadToHide()
				that.isLoaded=true
				uni.hideLoading()
       // that.loading = false
      });
    },
    // 套餐列表
    getGoodsBackage() {
      let that = this;
      let qsData = {
        store_id: this.storeId,
        page: that.listQuery.page,
        limit: that.listQuery.pageSize
      };
      that.$_get(GOODS_BACKAGE, qsData).then(res => {
        if (res.code === 1) {
        that.goodsList = that.goodsList.concat(res.data.list)
          if (res.data.list.length < that.listQuery.pageSize) {
            that.finished = true
          } else {
            that.listQuery.page++
          }
        } else {
          that.$common.msgToShow(res.msg)
        }
				uni.hideLoading()
        that.loading = false
      });
    },
    getStoreInfo() {
      let that = this;
      that.$_get(STORE_GET_INFO).then(res => {
        console.log('store_info', res)
        that.getGoodsCategory(res)
      });
    },
    // 商品分类列表
    getGoodsCategory(store) {
      store = store.code ? store : '';
      let that = this, _temp = [{id: -1, name: '精选套餐'}], categoryList = that.categoryList;
      that.$_get(GOODS_CATEGORY_LIST, {store_id: this.storeId}).then(res => {
        if(res.code === 1){
          _temp[0]['name'] = store.data.package_name
          if (store.code) {
            var package_position = store.data.package_position
            console.log('xinainainainiaa', package_position)
            if (package_position == 0) {
              categoryList = categoryList.concat(_temp)
              that.categoryList = categoryList.concat(res.data)
            } else if (package_position == 1) {
              res.data = categoryList.concat(res.data)
              that.categoryList = res.data.concat(_temp)
            } else if (package_position == 2) {
              res.data = categoryList.concat(res.data)
              that.categoryList = res.data
            } else {
              res.data = categoryList.concat(res.data)
              that.categoryList = _temp.concat(res.data)
            }
          } else {
            res.data = categoryList.concat(res.data)
            that.categoryList = _temp.concat(res.data)
          }
        } else {
          that.$common.msgToShow(res.msg)
        }
      });
    },
    // 加入购物车
    addCart(goods) {
      this.goodsId = goods.id;
      this.isPackage = goods && goods.is_package ? true : false
      this.cartShow = true;
    },
		cartIsShow(data){
			this.cartShow = data
    },
    // 选择分类
    changeCategory: debounce(function(id, name) {
      let that = this
	  uni.showLoading()
      that.categoryIdx = id;
	  that.$store.commit('setcategory', id)
      that.categoryName = name
	  that.finished = false
      that.listQuery.page = 1
      that.$storage.set('categoryIdx', id, false)
	  // xinqian
	  that.styleActive = {}
	  that.placeActive = {}
	  that.volActive = {}
	  that.priceActive = {}
      // that.$common.loadToShow()
	  that.isLoaded=false
      that.goodsList = []
      if (id === -2) {
        that.getGoodsList()
        that.goodsType = 'top'
      } else if (id === -1) {
        that.getGoodsBackage()
        that.goodsType = 'package'
      }else if(id === 0){
        that.$common.navigateTo('/pages/goods/integral');
			}else {
        that.getGoodsList()
        that.goodsType = 'general'
      }
    }, 150),
    // 过滤风格，产地，酒精度，价格
    fillterData (selectedOption) {
      if (selectedOption.type === 'style') {
        this.styleActive = selectedOption
      } else if (selectedOption.type === 'place') {
        this.placeActive = selectedOption
      } else if (selectedOption.type === 'vol') {
        this.volActive = selectedOption
      } else if (selectedOption.type === 'price') {
        this.priceActive = selectedOption
      }
	  this.finished = false
      this.listQuery.page = 1
	  this.isLoaded=false
      this.goodsList = []
      this.getGoodsList()
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  font-size: 14px;
}
.main_left_cont {
  background: #2a2a2a;
  height: 100%;
  width: 82vw;
	padding-top: 8vw;;
}
.main_list {
  padding: 0 19px 0 19px;
	margin-top: 66px;
}
.main_tit {
  position: relative;
}
.main_txt {
  position: absolute;
  width: 110px;
  text-align: center;
  line-height: 44px;
  font-size: 18px;
  background: #2a2a2a;
  top: 50%;
  margin-top: -26px;
  left: 50%;
  margin-left: -55px;
  color: #c4c4c4;
}
.main_line {
  width: 100%;
  height: 2px;
  background: #444444;
}
.main_items {
  flex-wrap: wrap;
  margin-top: 22px;
}
.main_item {
  background: #373737;
  margin-right: 11px;
  margin-bottom: 24px;
  box-shadow: 0 0 5px 2px rgba(200, 173, 103, .6);
  border-radius: 5px;
  position: relative;
}
.main_item:nth-child(4n + 4) {
  margin-right: 0;
}

.main_src {
  width: 192px;
  height: 192px;
  background: #333333;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}
.main_info {
  padding: 10px 6px;
  box-sizing: border-box;
  width: 192px;
  color: #f8f8f8;
}
.main_name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 8px;
  font-size: 14px;
}
.main_ename {
  font-size: 12px;
  height: 32px;
}
.main_box {
  margin-top: 8px;
  justify-content: space-between;
}
.main_price {
  font-size: 16px;
  line-height: 38px;
  color: red;
}
.main_price text {
  font-size: 12px;
}
.sale_price {
  font-size: 11px;
  line-height: 38px;
  text-decoration: line-through;
}
.main_add {
  width: 38px;
  height: 38px;
  background: #c8ad67;
  border-radius: 5px;
  color: #232323;
  font-size: 30px;
  text-align: center;
  font-weight: bold;
  line-height: 34px;
}

.main_right_cont {
  background: #232323;
  width: 18vw;
  position: fixed;
  right: 0;
	top: 8vw;
  height: calc(100vh - 8vw);
	overflow-y: scroll;
}
.r_item {
  box-sizing: border-box;
  padding-left: 14px;
  color: #c7c7c7;
  line-height: 50px;
  font-size: 18px;
  border: solid 1px rgba(255, 255, 255, 0);
  border-left: rgba(255, 255, 255, 0) 5px solid;
}
.addStyle {
  border: solid 1px #444444;
  border-left: #f3ca7e 5px solid;
  box-shadow: 0 0 1px #f3ca7e;
}
.noneGoods{
	height: 300px;
	line-height: 300px;
	color: #ffffff;
	font-size: 20px;
	text-align:center;
	width: 100%
}
.sale-out{
  position: absolute;
  width: 100px;
  height: 100px;
  bottom: 4vw;
  right: 5vw;
}
.is-top{
  position: absolute;
  width: 60px;
  height: 60px;
  left: 0;
  top: 0;
  border-top-left-radius: 5px;
}
</style>

<style>
/* .uni-input input {
  height: 40px !important;
} */
</style>
